#include "cv.h" 
#include "highgui.h" 
#include <stdio.h>  

int thresh = 200;

// A Simple Camera Capture Framework 
int main() {    
	CvCapture* capture = cvCaptureFromCAM( CV_CAP_ANY );
	if( !capture ) {
		fprintf( stderr, "ERROR: capture is NULL \n" ); 
		getchar();
		return -1;
	}    
	// Create a window in which the captured images will be presented   
	cvNamedWindow( "Webcam Capture", CV_WINDOW_AUTOSIZE );    
	cvNamedWindow( "Canny Edge Detection", CV_WINDOW_AUTOSIZE );   
	// Show the image captured from the camera in the window and repeat   
	while( 1 ) {
		// Get one frame
		IplImage *gray, *edge, *cedge;
		IplImage *frame = cvQueryFrame( capture );
		if( !frame ) {       
			fprintf( stderr, "ERROR: frame is null...\n" );
			getchar();
			break;
		}
		cedge = cvCreateImage(cvSize(frame->width,frame->height), IPL_DEPTH_8U, 3);
		gray = cvCreateImage(cvSize(frame->width,frame->height), IPL_DEPTH_8U, 1);
		edge = cvCreateImage(cvSize(frame->width,frame->height), IPL_DEPTH_8U, 1);
		cvCvtColor(frame, gray, CV_BGR2GRAY);
		cvSmooth( gray, edge, CV_BLUR, 3, 3, 0, 0 );
		cvNot( gray, edge );
		// Run the edge detector on grayscale
		cvCanny(gray, edge, (float)thresh, (float)thresh*3.0, 3);
		cvZero( cedge );
		// copy edge points
		cvCopy( frame, cedge, edge );

		cvShowImage( "Canny Edge Detection", edge );
		cvShowImage( "Webcam Capture", frame );
		// Do not release the frame!      

		//break if any key is pressed
		if(cvWaitKey(1) != -1) break;
	}    
	// Release the capture device housekeeping   
	cvReleaseCapture( &capture );
	cvDestroyWindow( "Canny Edge Detection" );   
	cvDestroyWindow( "Webcam Capture" );   
	return 0; 
} 